<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\ResponseException;
use App\Jobs\OrderPayEmailNotify;
use App\Models\GoodsSku;
use App\Models\Order;
use App\Models\OrderInfo;
use App\Models\SeckillGoods;
use App\Models\User;
use App\Task\PushMsgTask;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use Psy\Output\PassthruPager;
use Whoops\Exception\ErrorException;
use Hhxsv5\LaravelS\Swoole\Task\Task;
/**
 * Class 余额支付控制器
 * @package App\Http\Controllers\Api
 */
class BalancePayController extends Controller
{
    /**
     * 余额支付
     * User: ihome
     * @param Request $request
     * @throws ResponseException
     */
    public function balancePay(Request $request)
    {
        //获取订单号 查询未支付订单
        $order_sn = $request->input('order_sn');

        $order = Order::query()
            ->select('id', 'order_sn', 'price_total','order_type','active_id')
            ->where([
                'order_sn' => $order_sn,
                'status'   => 0,
                'user_id'=>auth('api')->id(),
            ])->lockForUpdate()->first();

        if ( ! $order) {
            throw new ResponseException(404,'没有找到订单，或者该订单已经支付过了，请返回个人中心查看');
        }

        //判断用户余额是否足够
        if(bccompNum(auth('api')->user()->balance,'<',$order->price_total)){
            throw new ResponseException(400,'用户余额不足，无法支付');
        }

        //开始减少并更新用户余额
        \DB::beginTransaction();

        try{
            $user = User::query()->select('id','balance','email')->where(['id'=>auth('api')->id()])->lockForUpdate()->first();

            $balance = bcsub($user->balance,$order->price_total,2);

            //更新用户余额

            $user->balance = $balance;
            $user->save();

            //更新订单
            $order->status = 1;
            $order->pay_type = 3;
            $order->pay_time = date('Y-m-d H:i:s',time());
            $order->save();
            //发送邮件
            dispatch(new OrderPayEmailNotify($user->email,$user->nick_name,$order_sn));
            //异步通知后台
            $task = new PushMsgTask([]);
            $ret = Task::deliver($task);

            \Log::info('订单通知异步任务：' . $ret);

            try{
                //判断是不是秒杀订单
                if($order->order_type == 2){
                    $goods = $order->orderInfo()->select('goods_id','sku_list')->first()->toArray();
                    //过期时间计算方法为 秒杀商品的过期 - 当前时间戳 + 600秒
                    $kill_goods_expired_time = SeckillGoods::query()->where(['goods_id'=>$goods['goods_id'],'kill_status'=>1])->value('end_time');
                    $key_expired_time = strtotime($kill_goods_expired_time) - time() + 600;
                    Redis::setex('already_shopping:'.$goods['goods_id'].':user_id:'.auth('api')->id(),$key_expired_time,$goods['goods_id']);

                    //删除创建订单的key
                    $key = 'create_sckill_order:'.$goods['goods_id'].':user_id:'.auth('api')->id().':sku:'.$goods['sku_list'].':order_sn:'.$order['order_sn'].':active_id:'.$order['active_id'];
                    Redis::del($key);

                    \Log::info('秒杀订单setget ==='.json_encode($goods).'==='.$kill_goods_expired_time);
                    \Log::info('秒杀订单key删除 ==='.$key);
                }else{
                    \Log::info('不是秒杀订单');
                }
            }catch (\Exception $e){
                \Log::info('付款操作失败：' . $e->getMessage());
            }

            //返回支付结果
            \DB::commit();

            return response()->json(['code'=>200,'msg'=>'支付成功','data'=>[]]);
        }catch (ErrorException $errorException){
            \DB::rollBack();
            //记录日志
            \Log::debug(date('Y-m-d H:i:s',time()) . '---支付异常---' . $errorException->getMessage());
            return response()->json(['code'=>500,'msg'=>'订单支付失败，请联系管理员','data'=>[]]);
        }
    }

    /**
     * 检查支付密码
     * User: ihome
     * @param Request $request
     */
    public function checkPayPswd(Request $request)
    {
        $password = $request->input('password');

        if(!password_verify($password,auth('api')->user()->pay_password)){
            //密码验证失败，增加失败次数，超过5次失败，必须重新修改支付密码
            if(auth('api')->user()->pay_error_count != 5){
                auth('api')->user()->increment('pay_error_count',1);
                throw new ResponseException(400,'密码错误，请重新输入');
            }else{
                //清空支付密码
                auth('api')->user()->update([
                    'pay_password'=>'',
                ]);
                throw new ResponseException(400,'密码错误次数太多，已锁定支付功能，请重新修改支付密码');
            }
        }else{
            throw new ResponseException(200,'ok');
        }
    }
}
